import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:stacked/stacked.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

/// 编辑个人资料视图模型
/// 管理编辑个人资料页面的数据和状态
class EditProfileViewModel extends BaseViewModel {
  final AuthFocus _authFocus;

  EditProfileViewModel(this._authFocus);

  UserFrame? _currentUser;
  UserFrame? get currentUser => _currentUser;

  String? _selectedAvatarPath;
  String? get selectedAvatarPath => _selectedAvatarPath;

  String _username = '';
  String get username => _username;

  String _signature = '';
  String get signature => _signature;

  /// 初始化数据
  Future<void> initialize() async {
    setBusy(true);
    try {
      await _loadCurrentUser();
    } finally {
      setBusy(false);
    }
  }

  /// 加载当前用户
  Future<void> _loadCurrentUser() async {
    _currentUser = await _authFocus.getCurrentUser();
    if (_currentUser != null) {
      _username = _currentUser!.username;
      _signature = _currentUser!.signature ?? '';
    }
    notifyListeners();
  }

  /// 设置用户名
  void setUsername(String value) {
    _username = value;
    notifyListeners();
  }

  /// 设置签名
  void setSignature(String value) {
    _signature = value;
    notifyListeners();
  }

  /// 选择头像
  Future<void> selectAvatar(BuildContext context) async {
    try {
      final List<AssetEntity>? selectedAssets = await AssetPicker.pickAssets(
        context,
        pickerConfig: const AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
        ),
      );

      if (selectedAssets == null || selectedAssets.isEmpty) {
        return; // 用户取消了选择
      }

      final asset = selectedAssets.first;

      // 将图片复制到本地目录
      final localPath = await _copyImageToLocal(asset);

      if (localPath != null) {
        _selectedAvatarPath = localPath;
        notifyListeners();
      }
    } catch (e) {
      // 错误处理
    }
  }

  /// 将图片复制到本地目录
  Future<String?> _copyImageToLocal(AssetEntity asset) async {
    try {
      // 获取应用文档目录
      final directory = await getApplicationDocumentsDirectory();
      final imagesDir = Directory('${directory.path}/profile_images');

      // 如果目录不存在，创建它
      if (!await imagesDir.exists()) {
        await imagesDir.create(recursive: true);
      }

      // 生成唯一的文件名
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final fileName = 'avatar_$timestamp.jpg';
      final filePath = '${imagesDir.path}/$fileName';

      // 读取图片数据
      final file = await asset.file;
      if (file == null) {
        return null;
      }

      // 复制文件到本地目录
      final localFile = File(filePath);
      await file.copy(localFile.path);

      // 返回本地路径（用于存储和显示）
      return localFile.path;
    } catch (e) {
      return null;
    }
  }

  /// 保存用户信息
  Future<bool> saveUserInfo() async {
    if (_currentUser == null) {
      return false;
    }

    setBusy(true);
    try {
      await _authFocus.updateUserInfo(
        account: _currentUser!.account,
        username: _username.trim().isEmpty ? null : _username.trim(),
        avatar: _selectedAvatarPath ?? _currentUser!.avatar,
        signature: _signature.trim().isEmpty ? null : _signature.trim(),
      );
      return true;
    } catch (e) {
      return false;
    } finally {
      setBusy(false);
    }
  }
}
